package com.igeek.ch02.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
 *@author wangpeng
 *2023/7/19 18:00
 *@description TODO
 */
public class JDBCUtilsByC3P0 {

    private static DataSource dataSource = new ComboPooledDataSource("mysql");

    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    public static Connection getConn(){
        Connection conn =tl.get();
        try {
            if(conn == null || conn.isClosed()){
                conn = dataSource.getConnection();
                tl.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭资源
    public static void close(Connection conn , Statement st , ResultSet rs){

        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
